package dao

import (
	"apedge/pkg/protocol"
	"fmt"
	"time"

	"github.com/jinzhu/gorm"
)

const (
	TableApedgeInference string = "t_apedge_inference"
)

const ()

type ApedgeInference struct {
	ID                     int64      `gorm:"primary_key" json:"id"`
	OrgId                  int64      `gorm:"not null" json:"orgId"`
	GroupId                int64      `gorm:"not null" json:"groupId"`
	UserId                 int64      `gorm:"not null" json:"userId"`
	UserName               string     `gorm:"not null;describe:'创建人'" json:"userName"`
	ServiceId              string     `gorm:"describe:'服务id'" json:"serviceId"`
	Name                   string     `gorm:"unique;size:255;not null;describe:'任务名称'" json:"name"`
	Describe               string     `gorm:"size:255;describe:'任务描述'" json:"describe"`
	Caller                 string     `gorm:"describe:'启动者'" json:"caller"`
	StartTime              int64      `gorm:"describe:'启动时间'" json:"startTime"`
	Url                    string     `gorm:"describe:'推理url'" json:"url"`
	Status                 string     `gorm:"describe:'服务状态'" json:"status"`
	Models                 string     `gorm:"describe:'模型'" json:"models"`
	Envs                   string     `gorm:"describe:'环境变量'" json:"envs"`
	NodeIds                string     `gorm:"describe:'推理节点'" json:"nodeIds"`
	ContainerImage         string     `gorm:"describe:'推理镜像'" json:"containerImage"`
	ContainerImageTag      string     `gorm:"describe:'推理镜像版本'" json:"containerImageTag"`
	ContainerRunCmd        string     `gorm:"describe:'容器运行命令'" json:"containerRunCmd"`
	ContainerRunParams     string     `gorm:"describe:'容器运行参数'" json:"containerRunParams"`
	ContainerPrivilegeMode bool       `gorm:"describe:'容器特权模式'" json:"containerPrivilegeMode"`
	ContainerResart        string     `gorm:"describe:'容器重启策略'" json:"containerResart"`
	ContainerNetwork       string     `gorm:"describe:'容器网络类型'" json:"containerNetwork"`
	ContainerPorts         string     `gorm:"describe:'容器网络端口'" json:"containerPorts"`
	CreatedAt              *time.Time `gorm:"notnull" json:"createdAt"`
	UpdatedAt              *time.Time `gorm:"notnull" json:"updatedAt"`
	DeletedAt              *time.Time `gorm:"default null" json:"deletedAt"`
}

type ApflowModel struct {
	Name         string `json:"name"`
	ID           int64  `json:"id"`
	PvcPath      string `json:"pvcPath"`
	Version      string `json:"version"`
	VersionId    int64  `json:"versionId"`
	DownloadLink string `json:"FileServerUri"`
}

func (ApedgeInference) TableName() string {
	return TableApedgeInference
}

func (t *ApedgeInference) Save(tx *gorm.DB) error {
	return tx.Save(t).Error
}

func (t *ApedgeInference) GetList(tx *gorm.DB, pageNum int64, pageSize int64, name string, sort string, userInfo *protocol.UserInfoAAA) ([]ApedgeInference, int64, error) {
	var list []ApedgeInference
	var temp []ApedgeInference
	var err error
	var count int64

	offset := (pageNum - 1) * pageSize
	query := tx.Table(t.TableName())

	// 按组织筛选
	query = query.Where("group_id = ?", userInfo.GroupId)
	name = "%" + name + "%"

	err = query.Where("name LIKE ?", name).Find(&temp).Count(&count).Error
	if err != nil {
		return nil, 0, err
	}
	// 排序
	sortMap := ParseSort(sort)
	for k, v := range sortMap {
		order := fmt.Sprintf("%s %s", k, v)
		query = query.Order(order)
	}
	err = query.Where("name LIKE ?", name).Limit(pageSize).Offset(offset).Find(&list).Error
	if err != nil {
		return nil, 0, err
	}

	return list, count, err
}

func (t *ApedgeInference) GetNumByName(tx *gorm.DB) (int64, error) {
	var count int64

	err := tx.Model(&ApedgeInference{}).Where("name = ?", t.Name).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, err
}

func (t *ApedgeInference) GetByServiceId(tx *gorm.DB) (*ApedgeInference, error) {
	var item ApedgeInference

	err := tx.Where("service_id = ?", t.ServiceId).Find(&item).Error
	if err != nil {
		return nil, err
	}
	return &item, err
}

func (t *ApedgeInference) DeleteByServiceId(tx *gorm.DB) error {
	return tx.Where("node_id = ?", t.ServiceId).Unscoped().Delete(&ApedgeInference{}).Error
}

func (t *ApedgeInference) UpdateByServiceId(tx *gorm.DB, data interface{}) error {

	err := tx.Model(&ApedgeInference{}).Where("service_id = ?", t.ServiceId).Updates(data).Error

	if err != nil {
		return err
	}
	return nil
}

func (t *ApedgeInference) GetListByServiceIds(tx *gorm.DB, serviceIds []string) ([]ApedgeInference, error) {
	var items []ApedgeInference

	err := tx.Where("service_id IN (?)", serviceIds).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return items, err
}
